package com.bruce.tool.search.solr.domain;

import com.google.common.collect.Lists;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.*;

/**
 * 功能 :
 * solr查询标准参数
 * exclude查询方式说明:
 * 开启之后
 * 1.在filterQuery的查询参数中,如果之后一个值的参数,会在前面自动加上tag前缀,例如:{!tag=cateId2}cateId2=123
 * 2.在facetQuery的查询参数中,增加ex前缀,例如:{!ex=cateId2}cateId2
 * @author : Bruce(刘正航) 上午2:00 2018/5/8
 */
@NoArgsConstructor(staticName = "build")
public class FacetQuerys implements Serializable {

    public static final Integer DEFAULT_MIN_COUNT = 1;

    @Getter
    private Integer minCount = DEFAULT_MIN_COUNT;

    private Set<String> facetFields = new HashSet<>(3);

    /**是否开启facet的exclude参数**/
    private static ThreadLocal<Map<String,Boolean>> excludeFields = new ThreadLocal<Map<String,Boolean>>();

    /**是否开启exclude查询方式**/
    public static boolean isEnableExclude(String field){
        Map<String,Boolean> fields = excludeFields.get();
        if( null == fields ){
            return false;
        }
        Boolean enable = fields.get(field);
        return null != enable;
    }

    /**
     * 设置是否开启exclude查询方式
     * exclude查询方式说明:
     * 开启之后
     * 1.在filterQuery的查询参数中,如果之后一个值的参数,会在前面自动加上tag前缀,例如:{!tag=cateId2}cateId2=123
     * 2.在facetQuery的查询参数中,增加ex前缀,例如:{!ex=cateId2}cateId2
     */
    public static void addExcludeField(String ... fields){
        Map<String,Boolean> exeFields = excludeFields.get();
        if( null == exeFields ){
            exeFields = new HashMap<>();
            excludeFields.set(exeFields);
        }
        for (String field : fields ) {
            exeFields.put(field,true);
        }
    }

    public final FacetQuerys add(String ...fields){
        this.addAll(Lists.newArrayList(fields));
        return this;
    }

    public final FacetQuerys addAll(Collection<String> fields){
        if(!CollectionUtils.isEmpty(fields) ){
            facetFields.addAll(fields);
        }
        return this;
    }

    public final boolean isFacetOn(){
        return facetFields.size() > 0;
    }

    public final String[] toArray(){
        Set<String> fields = new HashSet<>();
        for ( String field : facetFields ) {
            if( isEnableExclude(field) ){
                field = "{!ex="+field+"}"+field;
            }
            fields.add(field);
        }
        return fields.toArray(new String[]{});
    }

}
